package cs9322.assign3.operation;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

import cs9322.assign3.model.Order;

/**
 * Servlet implementation class Release
 */
public class Release extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Release() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		ClientConfig clientConfig = new DefaultClientConfig();
		Client client = Client.create(clientConfig);
		WebResource service = client.resource("http://localhost:8080/cs9322.assign3.coffee");
		String id = request.getParameter("id");
		
		Order o = service.path("starbucks").path("orders/"+id).accept(MediaType.TEXT_XML).get( Order.class);
		if(o.isPaid() == false){
			request.setAttribute("message", "The order has not been paid, you cannot release it");
			request.getRequestDispatcher("warning.jsp").forward(request, response);
		}else{
		o.setStatus("released");
		ClientResponse cr = service.path("starbucks").path("orders/"+id).type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML)
				   .put(ClientResponse.class, o);
		response.sendRedirect("main.jsp");
		}
	}

}
